package com.dalin.framework.action;

import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.util.Date;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;

import com.dalin.common.PropertyConst;
import com.dalin.common.pager.Condition;
import com.dalin.common.pager.PageInfo;
import com.dalin.common.utils.DateUtils;
import com.dalin.common.utils.ExcelUtils;
import com.dalin.common.utils.NumberUtils;
import com.dalin.common.utils.StringUtils;
import com.dalin.platform.loa.vo.WsCurrentUserInfo;
import com.opensymphony.xwork2.ActionSupport;

/*****************************************************************************
 * @content: Struts2框架前后台调度的调度者action基类                                                                   *
 * @author : 那建林                                                                                                                                 *
 * @crtDate: 2010-03-11                                                     *
 * @modDate: 2010-11-05                                                     *
 * @remark : 程序永远在不断的完善中进步                                                                                              *
 ****************************************************************************/
public abstract class StrutsTwoAction extends ActionSupport {
	protected static final Log log = LogFactory.getLog(ServletAction.class);
	
	/*************************************************************************
	 * @content: 获得HttpServletRequest对象
	 * @author : 那建林
	 * @crtDate: 2008-04-27
	 */
	protected final HttpServletRequest getReq() {
		return ServletActionContext.getRequest();
	}
	
	
	/*************************************************************************
	 * @content: 获得HttpServletResponse对象
	 * @author : 那建林
	 * @crtDate: 2008-04-27
	 */
	protected final HttpServletResponse getRes() {
		return ServletActionContext.getResponse();
	}
	
	
	/*************************************************************************
	 * @content: 根据cookie名称获取其值
	 * @param  : name cookie名称
	 * @author : 那建林
	 * @crtDate: 2010-11-05
	 * @modDate: 2010-11-05
	 */
	protected final String getCookieValue(String name) {
		String rtnStr = null;
		Cookie[] cc = getReq().getCookies();
		if (cc == null) return null;
		for (Cookie c : cc) {
			if (c.getName().equals(name)) {
				rtnStr = c.getValue();
				break;
			}
		}
		return rtnStr;
	}
	
	
	/*************************************************************************
	 * @content: 获得绝对物理路径,eg: D:/sw/tomcat-5.5.26/webapps/cutedalin/
	 * @author : 那建林
	 * @crtDate: 2010-11-05
	 * @modDate: 2010-11-05
	 */
	protected final String getAbsolutePhysicalPath() {
		return getReq().getSession().getServletContext()
				.getRealPath(PropertyConst.SINGLE_SLASH)
				.replaceAll("\\\\", PropertyConst.SINGLE_SLASH);
	}
	
	
	/*************************************************************************
	 * @content: 获得当前登录用户
	 * @remak  : 这个方法写的太牛B了，省了多少事
	 * @author : 那建林
	 * @crtDate: 2009-05-18
	 * @modDate: 2009-06-05
	 */
	protected final WsCurrentUserInfo getCurrentUser() {
		return (WsCurrentUserInfo) getReq().getSession(false)
			.getAttribute(PropertyConst.USER_SESSION_NAME);
	}
	/*************************************************************************
	 * @content: 通过前台传过来的字条串，给查询条件动态赋值
	 * @param  : Class Condition条件
	 * @param  : json字符串{name:value}
	 * @author : 那建林
	 * @crtDate: 2009-05-18
	 * @modDate: 2009-06-05
	 * @remak  : 这个方法写的太牛B了，省了多少事
	 */
	protected final <N> N getCond(
			Class<N> c, String condStr, Integer start, Integer limit) throws Exception {
		System.out.println(this.getClass().getSimpleName() + "==查询字符串为======" + condStr);
		System.out.println(this.getClass().getSimpleName() + "==起始数======" + start);
		System.out.println(this.getClass().getSimpleName() + "==每页显示数======" + limit);
		Condition cond = (Condition) c.newInstance();
		cond.setStartRow(start);
		cond.setPageSize(limit);
		if (StringUtils.isBlank(condStr)) return (N) cond;
		JSONObject jo = JSONObject.fromObject(condStr);
		Field[] fieldArr = c.getDeclaredFields();
		Object value = null;
		for (Field f : fieldArr) {
			f.setAccessible(true);
			value = jo.get(f.getName());
			if (String.class.equals(f.getType())) {
				f.set(cond, value);
			} else if (Long.class.equals(f.getType())) {
				if (value != null && NumberUtils.isIntegerType(value.toString())) {
					f.set(cond, Long.parseLong(value.toString()));
				}
			} else if (Integer.class.equals(f.getType())) {
				if (value != null && NumberUtils.isIntegerType(value.toString())) {
					f.set(cond, Integer.parseInt(value.toString()));
				}
			} else if (Date.class.equals(f.getType())) {
				if (value != null) {
					f.set(cond, DateUtils.getDate(value.toString()));
				}
			}
		}
		return (N) cond;
	}
	
	
	/*************************************************************************
	 * @content: 设置HttpServletResponse返回头
	 * @author : 那建林
	 * @crtDate: 2008-04-27
	 */
	private final void setResHeader() {
		getRes().setCharacterEncoding("UTF-8");
		getRes().setContentType("application/json");
	}
	
	
	/*************************************************************************
	 * @content: 设置HttpServletResponse返回html内容
	 * @param  : 返回的html字串
	 * @author : 那建林
	 * @crtDate: 2008-08-17
	 */
	protected final void setResHtml(String s) throws Exception {
		getRes().setCharacterEncoding("UTF-8");
		getRes().setContentType("text/html;charset=UTF-8");
		getRes().getWriter().print(s);
	}
	
	
	/*************************************************************************
	 * @content: 设置HttpServletResponse返回内容
	 * @param  : 多态对象
	 * @author : 那建林
	 * @throws IOException 
	 * @crtDate: 2008-05-21 02:01
	 */
	protected final void setResContent(String s) throws IOException {
		System.out.println(this.getClass().getSimpleName()
				+ " 返回值=========" + s);
		setResHeader();
		getRes().getWriter().print(s);
	}
	protected final void setResContent(boolean successful,
			String info) throws IOException {
		StringBuffer buf = new StringBuffer("{success:");
		buf.append(successful).append(PropertyConst.COMMA)
			.append("info:'").append(info).append("'");
		buf.append("}");
		setResContent(buf.toString());
	}
	protected final void setResContent(boolean successful,
			List dataList) throws IOException {
		setResContent("{success:" + successful + ", dataList:"
				+ JSONArray.fromObject(dataList).toString() + "}");
	}
	protected final void setResContent(Exception e) throws Exception {
		String errorMsg = e.getMessage();
		if (errorMsg == null) errorMsg = "空指针错误,请联系管理员TEACHER NA";
		setResContent(false, errorMsg.trim().replaceAll("\n", ""));
	}
	protected final void setResContent(PageInfo pageInfo) throws Exception {
		setResContent(JSONObject.fromObject(pageInfo).toString());
	}
	protected final void setResContent(List l) throws Exception {
		setResContent(JSONArray.fromObject(l).toString());
	}
	protected final void setResContent(Object obj) throws Exception {
		setResContent("{data:[" 
				+ JSONObject.fromObject(obj).toString() + "]}");
	}
	protected final void setRootResContent(List l) throws Exception {
		setResContent("{dataList:"
				+ JSONArray.fromObject(l).toString() + "}");
	}
	
	
	
	/*************************************************************************
	 * @content: 根据数据导出excel表格
	 * @param  : dataList 数据集合
	 * @param  : sheetName sheet名称
	 * @param  : fileName 文件名
	 * @author : 那建林
	 * @crtDate: 2010-12-13
	 */
	protected void exportExcel(
			List<List<String>> dataList, String sheetName, String fileName) throws Exception {
		OutputStream out = getRes().getOutputStream();
		getRes().setHeader("Content-disposition","attachment;filename="
				+ fileName + ".xls");
		getRes().setContentType("application/vnd.ms-excel;charset=UTF-8");
		ExcelUtils.writeNewExcel(dataList, out, sheetName);
        out.flush();
        out.close();
	}
	
	/*************************************************************************
	 * @content: 获得请求路径,不包括serverName, 如:/autocode/glbGeneratorKeyManager.html
	 * @author : 那建林
	 * @crtDate: 2010-12-22 23:26:28
	 * @modDate: 2010-12-22 23:26:28
	 */
	protected String getSimpleRequestURI() {
		return getReq().getRequestURI().substring(
				getReq().getContextPath().length());
	}
	
	
	protected final void printObj(Object obj) {
		StringUtils.printObj(obj);
	}
	protected final void printInfo(Object... objs) {
		StringUtils.printInfo(this.getClass(), objs);
	}
}
